var stasi = {
    visits: {
        visits: [],
        newVisits: 0
    },
    init: function() {
        xmldoc.request();
        stasi.getUser();
        if (!stasi.user) {
            return;
        }
        stasi.getLocale();
        stasi.injectVisits();
        stasi.mainloop();
    },
    getUser: function() {
        stasi.user = $.cookie("c_user");
    },
    getLocale: function() {
        stasi.locale = $("html").attr("lang").toLowerCase();
        if (!(stasi.locale in languages)) stasi.locale = "en";
    },
    injectVisits: function() {
        gui.initializeSite();
        stasi.getVisits();
    },
    getVisits: function() {
        var message = {
            cmd: "getVisits",
            url: config.url,
            payload: {
                user: stasi.user
            }
        };
        var func = function(data) {
            if (data === "error") {
                stasi.visits.error = languages[stasi.locale].server_not_available;
            } else {
                stasi.visits.error = undefined;
                stasi.visits = data;
                for (var i = 0; i < stasi.visits.visits.length; i++) if (stasi.visits.visits[i].deletedUser == true) {
                    stasi.visits.visits[i].id = 0;
                    stasi.visits.visits[i].name = languages[stasi.locale].deleted_user;
                }
                gui.updateVisitorButton(stasi.visits.newVisits);
            }
        };
        if (chrome.extension.sendMessage) chrome.extension.sendMessage(message, func); else chrome.extension.sendRequest(message, func);
        setTimeout(stasi.getVisits, 12e4);
    },
    mainloop: function() {
        stasi.getSiteOwner();
        setTimeout(stasi.mainloop, 1e3);
    },
    getSiteOwner: function() {
        tmp = $("#pagelet_timeline_main_column").attr("data-gt");
        if (tmp != null || tmp != undefined) {
            owner = JSON.parse(tmp).profile_owner;
            if (owner != stasi.owner) {
                stasi.owner = owner;
                stasi.visit(owner);
            }
        }
    },
    visit: function(owner) {
        if (owner == stasi.user) return;
        var message = {
            cmd: "visit",
            url: config.url,
            payload: {
                visitor: stasi.user,
                visited: owner
            }
        };
        if (chrome.extension.sendMessage) chrome.extension.sendMessage(message); else chrome.extension.sendMessage(message);
    },
    resetNewVisits: function() {
        stasi.visits.newVisits = 0;
        var message = {
            cmd: "visited",
            url: config.url,
            payload: {
                user: stasi.user
            }
        };
        if (chrome.extension.sendMessage) chrome.extension.sendMessage(message); else chrome.extension.sendMessage(message);
        gui.updateVisitorButton(stasi.visits.newVisits);
    }
};

$(document).ready(function() {
    stasi.init();
});